package com.cyy.activitylifecycleyanalysisdemo.adapter;

import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.cyy.activitylifecycleyanalysisdemo.R;

import java.util.List;

/**
 * Created by YYCHEN on 2018/1/16.
 */

public abstract class RecyclerViewSimpleAdapter<T>  extends RecyclerView.Adapter<RecyclerViewSimpleAdapter.ViewHolder>{

    private List<T> dataList;

    public List<T> getDataList() {
        return dataList;
    }

    public void setDataList(List<T> dataList) {
        this.dataList = dataList;
    }

    public RecyclerViewSimpleAdapter(@Nullable List<T> dataList, OnItemClickListener<T> listener){
        this.dataList = dataList;
        mOnClickListener = listener;
    }

    @Override
    public RecyclerViewSimpleAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View root = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_list_item, parent, false);
        return new ViewHolder(root);
    }

    @Override
    public void onBindViewHolder(RecyclerViewSimpleAdapter.ViewHolder holder, final int position) {
        bindData(holder, dataList.get(position));
        holder.tv_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(mOnClickListener != null){
                    mOnClickListener.onClick(v, position, dataList.get(position));
                }
            }
        });
    }

    public abstract void bindData(RecyclerViewSimpleAdapter.ViewHolder holder, T data);

    @Override
    public int getItemCount() {
        return dataList == null? 0: dataList.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder{
        public TextView tv_name;
        public ViewHolder(View itemView) {
            super(itemView);
            tv_name = (TextView) itemView;
        }
    }

    public void setmOnClickListener(OnItemClickListener mOnClickListener) {
        this.mOnClickListener = mOnClickListener;
    }

    private OnItemClickListener mOnClickListener;
    public interface OnItemClickListener<T>{
        void onClick(View view, int position, T data);
    }
}
